layui.define(['element','layer','laytpl','form'], function (exports) {
    var $ = layui.jquery;
    var laytpl = layui.laytpl;
    var $pageFrame;
    var $selectLi = null;
    var form = layui.form;
    var element = layui.element;
    var editPwdForm = layui.Form('editPwdForm');
    var mySetingForm=layui.Form('mySetingForm');
    var colorStyleENUM = {
         '1': 'layui-bg-blue'
        ,'2': 'layui-bg-green'
        ,'3': 'layui-bg-cyan'
    }
    var busStyle=1;
    var menuStyle=1;

    var layuiAdmin = new function () {
        /**
         * 初始化
         * @param url
         */
        this.init = function (url) {
            var loading = layer.load(0, {shade: false, time: 2 * 1000});
            var msg =this.checkApi();
            if (msg != true){
                layer.close(loading);
                layer.alert('系统出小差了,请稍后再试!',
                    {
                        btnAlign: 'c',
                        title:'错误',
                        icon: 2,
                        btn: ['刷新一下'] //按钮
                    },
                    function(){
                        location.reload()
                    }
                );
                return ;
            }
            this.initUser();
            this.initNav();
            this.initEnum();
            this.initTableCols();
            this.initBaseDist();
            layer.close(loading);
        }
        this.checkApi=function () {
            var msg = true;
            $.ajax({
                url: SopConfig.url()+'/sys/info',
                type: 'get',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                async: false,
                error: function (xhr, textstatus, thrown) {
                    msg = '系统出小差了，请稍后再试！';
                }
            });
            return msg;
        }
        //初始化基础业务字典
        this.initBaseDist=function () {
            //初始化用户
            common.ajax.get('/common/get-conf-dist', {}, function (resp) {
                if(resp.baseContfigList){
                    resp.baseContfigList.forEach(function (json) {
                        var config=(typeof json ==='object')?json:JSON.parse(json);
                        console.log('init config',"baseConfig."+config.paramKey,config.paramValue);
                        common.util.setConfig("baseConfig."+config.paramKey,config.paramValue)
                    })
                }
                if(resp.baseDistlist){
                    resp.baseDistlist.forEach(function (json) {
                        var config=(typeof json ==='object')?json:JSON.parse(json);
                        console.log('init baseDist',"baseDist."+config.distCode,config);
                        common.util.setDist("baseDist."+config.distCode,config.distData)
                    })
                }

            });
        }
        //初始化用户信息
        this.initUser=function () {
            //初始化用户
            common.ajax.get('/sys/user/info', {}, function (resp) {
                var userInfo = resp.data;
                var entInfo = resp.ent;
                var userInfoExt=JSON.parse(userInfo.userExt);
                $('#userName').text(userInfo.userName);
                if(!userInfoExt)
                    userInfoExt={"busStyle":"1","menuStyle":"1","colorStyle":"3","webStyle":"1"};
                var colorStyle=userInfoExt.colorStyle||1;
                var webStyle=userInfoExt.webStyle||1;
                menuStyle=userInfoExt.menuStyle||1;
                console.log('userInfoExt.busStyle',userInfoExt.busStyle)
                busStyle=userInfoExt.busStyle||"1";
                common.util.setBusStyle(busStyle);
                var contentHtml="";
                if(busStyle==1){
                    contentHtml='<div class="layui-tab"  lay-filter="layuiAdminTab" id="top_tabs_box">\n' +
                        '        <ul class="layui-tab-title" id="top_tabs">\n' +
                        '            <li class="layui-this" id="layuiAdminHomeTabId" lay-id="">首页</li>\n' +
                        '        </ul>\n' +
                        ' <!--选项卡操作-->\n' +
                        '            <ul class="layui-nav closeBox">\n' +
                        '                <li class="layui-nav-item">\n' +
                        '                    <a href="javascript:;">更多操作</a>\n' +
                        '                    <dl class="layui-nav-child">\n' +
                        '                        <dd><a href="javascript:;" data-page-close="refresh"><i class="layui-icon layui-icon-refresh-3"></i>刷新当前</a></dd>\n' +
                        '                        <dd><a href="javascript:;" data-page-close="other"><i class="layui-icon layui-icon-close"></i> 关闭其他</a></dd>\n' +
                        '                        <dd><a href="javascript:;" data-page-close="all"><i class="layui-icon layui-icon-close-fill"></i> 关闭全部</a></dd>\n' +
                        '                    </dl>\n' +
                        '                </li>\n' +
                        '            </ul>\n'+
                        '        <div class="layui-tab-content">\n' +
                        '            <div class="layui-tab-item layui-show"> <iframe id="pageFrame" src=\'index/welcome.html\' frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%"  style="display:block"></iframe></div>\n' +
                        '        </div>\n' +
                        '    </div>';
                }else{
                    contentHtml='<iframe id="pageFrame" src=\'index/welcome.html\' frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%"  style="display:block"></iframe>';
                }
                $('.page-content').html(contentHtml);
                $pageFrame=$("#pageFrame");

                $("div.container").addClass(colorStyleENUM[colorStyle]);
                if(webStyle==="2"){
                    $("div.page-content").addClass('layui-container');
                }
                userInfo.userExt=userInfoExt;
                common.util.setUserInfo(JSON.stringify(userInfo));
                common.util.setEntInfo(JSON.stringify(entInfo));

            });
        }
        /**
         * 初始化菜单信息
         */
        this.initNav=function () {
            common.ajax.get('sys/menu/nav', {}, function (resp) {
                var getLeftTpl = nav_left_tpl.innerHTML
                    ,getTopTpl = nav_top_tpl.innerHTML
                    ,leftView = $('#nav')
                    ,topView = $('#topNav');
                common.auth.init(resp.permissions,resp.roles);
                laytpl(getLeftTpl).render(resp.menuList, function(html){
                    leftView.html( html);
                    $(".nav-title").on("click",function (event) {
                        $(this).parent().siblings().each(function () {
                            $(this).find("ul").hide(50);
                        })
                        $(this).next().toggle(50);
                        $(this).find("i").eq(1).toggleClass("open").toggleClass("close");
                    });
                });
                laytpl(getTopTpl).render(resp.menuList, function(html) {
                    topView.html( html);
                    element.render('nav');
                });
                if(menuStyle==="1"){
                    topView.hide();
                    leftView.show();
                    leftView.parent().parent().css("position","absolute");
                    $('.left_open').show();
                    $('.page-content').removeClass("page-content-top");
                }else if(menuStyle==="2"){
                    topView.show();
                    leftView.hide();
                    leftView.parent().parent().css("position","static");
                    $('.page-content').addClass("page-content-top");
                    $('.left_open').hide()
                }

            });
        }
        /**
         * 初始化表格项
         */
        this.initTableCols=function () {
            common.ajax.post('/common/get-table-cols',{}, function (resp) {
                //console.log("table cols", resp.data);
                $.each(resp.data, function () {
                    //console.log(this.tableKey,this.tableData);
                    common.util.setSession(this.tableKey, JSON.stringify(this.tableData));
                    //console.log("读取",sessionStorage.getItem(this.tableKey))
                })
            })
        }

        /**
         * 初始化数据字典
         */
        this.initEnum=function () {
            common.ajax.get('/common/enums', {}, function (resp) {
                //console.log("enum datas",resp.data);
                $.each(resp.data,function () {
                    console.log("init enum ",this.key,JSON.stringify(this.value));
                    common.util.setSession(this.key,JSON.stringify(this.value));
                })
            })
        }
        /**
         * 判断窗口是否已打开
         * @param tabId
         **/
        this.checkTab = function (tabId) {
            // 判断选项卡上是否有
            var checkTab = false;
            $(".layui-tab-title li").each(function () {
                var checkTabId = $(this).attr('lay-id');
                if (checkTabId != null && checkTabId == tabId) {
                    checkTab = true;
                }
            });
            if (checkTab == false) {
                return false;
            }

            // 判断sessionStorage是否有
            var layuiAdminTabInfo = JSON.parse(sessionStorage.getItem("layuiAdminTabInfo"));
            if (layuiAdminTabInfo == null) {
                layuiAdminTabInfo = {};
            }
            var check = layuiAdminTabInfo[tabId];
            if (check == undefined || check == null) {
                return false;
            }
            return true;
        };

        /**
         * 打开新窗口
         * @param tabId
         * @param href
         * @param title
         */
        this.addTab = function (tabId, href, title, addSession) {
            if (addSession == undefined || addSession == true) {
                var layuiAdminTabInfo = JSON.parse(sessionStorage.getItem("layuiAdminTabInfo"));
                if (layuiAdminTabInfo == null) {
                    layuiAdminTabInfo = {};
                }
                layuiAdminTabInfo[tabId] = {href: href, title: title}
                sessionStorage.setItem("layuiAdminTabInfo", JSON.stringify(layuiAdminTabInfo));
            }
            element.tabAdd('layuiAdminTab', {
                title: title + '<i data-tab-close="" class="layui-icon layui-unselect layui-tab-close">ဆ</i>' //用于演示
                , content: '<iframe  id="'+tabId+'" name="'+tabId+'"width="100%" height="100%" frameborder="0"  src="' + href + '"></iframe>'
                , id: tabId
            });
        };

        /**
         * 删除窗口
         * @param tabId
         */
        this.delTab = function (tabId) {
            var layuiAdminTabInfo = JSON.parse(sessionStorage.getItem("layuiAdminTabInfo"));
            if (layuiAdminTabInfo != null) {
                delete layuiAdminTabInfo[tabId];
                sessionStorage.setItem("layuiAdminTabInfo", JSON.stringify(layuiAdminTabInfo))
            }
            element.tabDelete('layuiAdminTab', tabId);
        };
        /**
         * 刷新窗口
         * @param tabId
         */
        this.refreshTab = function (tabId) {
            $("iframe[name='"+tabId+"']").attr('src', tabId);
        };



        /**
         * 切换选项卡
         **/
        this.changeTab = function (tabId) {
            element.tabChange('layuiAdminTab', tabId);
        };

        /**
         * Hash地址的定位
         */
        this.hashTab = function () {
            var layId = location.hash.replace(/^#/, '');
            element.tabChange('layuiAdminTab', layId);
            element.on('tab(layuiAdminTab)', function (elem) {
                location.hash = $(this).attr('lay-id');
            });
        };

        /**
         * 判断是否为手机
         */
        this.checkMobile = function () {
            var ua = navigator.userAgent.toLocaleLowerCase();
            var pf = navigator.platform.toLocaleLowerCase();
            var isAndroid = (/android/i).test(ua) || ((/iPhone|iPod|iPad/i).test(ua) && (/linux/i).test(pf))
                || (/ucweb.*linux/i.test(ua));
            var isIOS = (/iPhone|iPod|iPad/i).test(ua) && !isAndroid;
            var isWinPhone = (/Windows Phone|ZuneWP7/i).test(ua);
            if (!isAndroid && !isIOS && !isWinPhone) {
                return false;
            } else {
                return true;
            }
        };

        /**
         * 判断链接是否有效
         * @param url
         * @returns {boolean}
         */
        this.checkUrl = function (url) {
            var msg = true;
            $.ajax({
                url: url,
                type: 'get',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                async: false,
                error: function (xhr, textstatus, thrown) {
                    msg = 'Status:' + xhr.status + '，' + xhr.statusText + '，请稍后再试！';
                }
            });
            return msg;
        };
        this.clickTab=function (that) {
            if($('#top_tabs li').length>10){
                common.util.error("当前打开的菜单超过10个,请关闭后再操作");
                return ;
            }
            var tabId = that.attr('base-href'),
                href = that.attr('base-href'),
                title = that.text(),
                target = that.attr('target');
            if (target == '_blank') {
                window.open(href, "_blank");
                return false;
            }
            if(!href)return false;
                title = title.replace(/ /g,'');

            // 拼接参数
            var menuParameId = $(this).attr('base-href-mpi');
            if(menuParameId){
                if (href.indexOf("?") > -1) {
                    href = href + '&mpi=' + menuParameId;
                    tabId = href;
                } else {
                    href = href + '?mpi=' + menuParameId;
                    tabId = href;
                }
            }else{
                tabId = href;
            }
            if (tabId == null || tabId == undefined) {
                tabId = new Date().getTime();
            }
            // 判断该窗口是否已经打开过
            var checkTab = layuiAdmin.checkTab(tabId);
            if (!checkTab) {
                layuiAdmin.addTab(tabId, href, title, true);
            }
            element.tabChange('layuiAdminTab', tabId);
            //layuiAdmin.tabRoll();
        }
    }




    $('#mySeting').on('click', function (event) {
        var mySetingPro = my_seting_ro.innerHTML
        var userInfo=common.util.getUserInfo();
        laytpl(mySetingPro).render(userInfo.userExt, function(html){
            layer.open({
                type: 1,
                area: ['450px', '280px'],
                fix: false, //不固定
                shadeClose: true,
                shade:0.4,
                title: '个性化设置',
                content: html,
                success: function(layero, index){
                    form.render();    // 表单渲染
                    mySetingForm=layui.Form('mySetingForm');
                    form.on('submit(bind)', function(data) {     // 打印data就可以看到form表单提交的数据
                        var param = mySetingForm.getData();
                        console.log(param);
                        common.ajax.post('/sys/user/updateExt', param, function (resp){
                            userInfo.userExt=param;
                            common.util.setUserInfo(JSON.stringify(userInfo));
                        })
                        return false;
                    });
                    $('.colorStyle').on('click', function (event) {
                        $(this).siblings().each(function(){
                            $(this).html($(this).attr("text"));
                        });
                        $(this).html('<i class="layui-icon">&#xe605;</i>'+$(this).attr("text"));
                        $(this).siblings()[0].value=$(this).attr("val");
                        $("div.container")
                            .removeClass(colorStyleENUM["1"])
                            .removeClass(colorStyleENUM["2"])
                            .removeClass(colorStyleENUM["3"])
                            .addClass(colorStyleENUM[$(this).attr("val")]);
                        layero.find('.sub-bindbtn').click();
                        return false;
                    })
                    form.on('radio(webStyle)', function(data){
                        if(data.value==="2"){
                            $("div.page-content").addClass('layui-container');
                        }else{
                            $("div.page-content").removeClass('layui-container');
                        }
                        layero.find('.sub-bindbtn').click();
                    });

                    form.on('radio(busStyle)', function(data){
                        layero.find('.sub-bindbtn').click();
                        if(confirm("菜单显示模式切换成功,立即刷新系统")){
                            location.reload();  //实现页面重新加载
                        }
                    });
                    form.on('radio(menuStyle)', function(data){
                        if(data.value==="1"){
                            $('#nav').show();
                            $('#topNav').hide();
                            $('#nav').parent().parent().css("position","absolute")
                            $('.left_open').show();
                            $('.page-content').removeClass("page-content-top");


                        }else if(data.value==="2"){
                            $('#nav').hide();
                            $('#topNav').show();
                            $('#nav').parent().parent().css("position","static");
                            $('.left_open').hide();
                            $('.page-content').addClass("page-content-top");
                        }
                        layero.find('.sub-bindbtn').click();
                    });
                }
            });
        });
    });





    $('#editPwd').on('click', function (event) {
        layer.open({
            type: 1,
            area: ['400px', '280px'],
            fix: false, //不固定
            shadeClose: true,
            shade:0.4,
            title: '修改密码',
            content: $('#editPwdPro'),
            btn: ['确认', '关闭'], //只是为了演示
            success: function(layero, index){
                form.render();    // 表单渲染
                form.on('submit(bind)', function(data) {     // 打印data就可以看到form表单提交的数据
                    var param = editPwdForm.getData();
                    common.ajax.post('/sys/user/password', param, function (resp) {
                        layer.alert('修改成功', function () {
                            layer.closeAll();
                        })
                    })
                    return false;
                });

            },yes: function(index, layero){
                layero.find('.sub-bindbtn').click();    // 这一句就是点击确认按钮触发form的隐藏提交
            }
            ,btn2: function(){
                layer.closeAll();
            }
        });
    })
    form.verify({
        password: [
        /^[\S]{6,12}$/
        ,'旧密码必须6到12位，且不能为空'
        ],
        newPassword:[
            /^[\S]{6,12}$/
            ,'新密码必须6到12位，且不能出现空格'
        ],
        newPassword2: function(value, item){
            if(value!=$("#newPassword").val()){
                return '两次密码输入不一致\'_\'';
            }
        }
    });
    $('.left-nav').on('click', 'li', function (event) {
        var $tagLi = $(this);
        var $tagA = $tagLi.find('a').eq(0);
        if(busStyle==1){
            layuiAdmin.clickTab($tagA);
        }else{


            var href = $tagA.attr('base-href');
            if (href) {
                $pageFrame.prop('src',href + '?q=' + new Date().getTime());
                if ($selectLi) {
                    $selectLi.removeClass('active')
                }
                $selectLi = $tagLi.addClass('active');
            }
        }
        return false;
    });
    //一些事件监听
    element.on('nav(top-nav)', function(data){
        if(busStyle==1){
            layuiAdmin.clickTab($(this));
        }else {
            var $tagA = $(data);
            var href = $tagA.attr('base-href');
            if (href == 'no') return;
            $pageFrame.prop('src', href + '?q=' + new Date().getTime());
        }
    });

    /**
    * 选项卡操作
    */
    $('body').on('click', '#top_tabs', function () {
    })

    $('body').on('click', '[data-page-close]', function () {
        var closeType = $(this).attr('data-page-close');
        $(".layui-tab-title li").each(function () {
            tabId = $(this).attr('lay-id');
            var id = $(this).attr('id');
            if (id != 'layuiAdminHomeTabId') {
                var tabClass = $(this).attr('class');
                if (closeType == 'all') {
                    layuiAdmin.delTab(tabId);
                } else if (closeType == 'refresh') {
                    layuiAdmin.refreshTab(tabId);
                }else {
                    if (tabClass != 'layui-this') {
                        layuiAdmin.delTab(tabId);
                    }
                }
            }
        });
        //layuiAdmin.tabRoll();
    });

    /**
     * 关闭选项卡
     **/
    $('body').on('click', '[data-tab-close]', function () {
        $parent = $(this).parent();
        tabId = $parent.attr('lay-id');
        if (tabId != undefined || tabId != null) {
            layuiAdmin.delTab(tabId);
        }
        //layuiAdmin.tabRoll();
    });

    $('.container .left_open i').click(function(event) {
        if($('.left-nav').css('left')=='0px'){
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        }else{
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if($(window).width()<768){
                $('.page-content-bg').show();
            }
        }
    });

    window.getIndexTab=function () {
       return  $("#top_tabs_box li.layui-this").attr("lay-id");
    };
    exports("layuiAdmin", layuiAdmin);
});
